<template>
  <div class="app-container">

    <!-- 搜索区 -->
    <el-form v-if="$store.getters.loginType===0" ref="queryForm" :model="queryParam" size="small" :inline="true">
      <el-form-item label="商家名称" prop="name">
        <el-input
          v-model="queryParam.name"
          placeholder="请输入商家名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParam.status"
          placeholder="审核状态"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in auditList"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="createTimeValue"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="btnSearch">搜索</el-button>

      </el-form-item>
    </el-form>

    <!--功能区-->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
        >导出</el-button>
      </el-col>
    </el-row>

    <!-- 数据展示区table-->
    <el-table v-loading="loading" :data="tableData.rows" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" prop="id" width="100" />
      <el-table-column label="商家名称" prop="name" :show-overflow-tooltip="true" />
      <el-table-column label="商家地址" prop="address" :show-overflow-tooltip="true" />
      <el-table-column label="联系电话" prop="phone" :show-overflow-tooltip="true" />
      <el-table-column label="登录名" prop="loginName" :show-overflow-tooltip="true" />
      <el-table-column label="审核状态">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status===1">未审核</el-tag>
          <el-tag v-else type="success">已审核</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="商家图像">
        <template slot-scope="scope">
          <img v-if="scope.row.picture" :src="scope.row.picture" width="150">
          <el-tag v-else type="danger">未上传图像</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="创建时间" align="center" prop="createTime" />

      <el-table-column label="操作" align="left" width="300" class-name="small-padding fixed-width">
        <template slot-scope="scope">

          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
          >查看详情</el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>

          <el-button
            v-if="$store.getters.loginType===1"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleChangePwd(scope.row)"
          >更改密码</el-button>

          <el-button
            v-if="$store.getters.loginType===0 && scope.row.status===1"
            size="mini"
            type="text"
            icon="el-icon-finished"
            @click="handleAduit(scope.row)"
          >审核通过</el-button>

        </template>
      </el-table-column>
    </el-table>

    <!--分页条 -->
    <div style="margin-top: 10px;">
      <el-pagination
        v-if="tableData.total>0"
        :current-page="queryParam.page"
        :page-sizes="[10, 20, 30, 40,50,100]"
        :page-size="queryParam.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="tableData.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 显示详情-->
    <el-dialog title="商家详情" :visible.sync="openDetail" width="800px" append-to-body>
      <el-form label-width="100px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="登录名">
              {{ formDetail.loginName }}
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="商家名称">
              {{ formDetail.name }}
            </el-form-item>

          </el-col>

          <el-col :span="8">
            <el-form-item label="联系电话">
              {{ formDetail.phone }}
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="商家地址">
              {{ formDetail.address }}
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="商家图像">
              <img v-if="formDetail.picture" :src="formDetail.picture" width="150">
              <el-tag v-else type="danger">未上传图像</el-tag>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="商家位置">
              <BaiduDisplay v-if="formDetail.id" :item-data="formDetail" />

            </el-form-item>
          </el-col>

        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="openDetail=false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 地图选择器-->
    <el-dialog title="位置选择器" :visible.sync="mapShow" width="800px" append-to-body :close-on-click-modal="false">
      <BaiduAddress v-if="form.id" :item-data="form" @myclick="handlerLocation" />
    </el-dialog>

    <!-- 新增和修改对话框-->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body :close-on-click-modal="false" :before-close="cancelForm">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="登录名" prop="loginName">
          <el-input v-model="form.loginName" placeholder="请输入登录名称(唯一)" />
        </el-form-item>

        <el-form-item label="商家名称" prop="name">
          <el-input v-model="form.name" placeholder="商家名称" />
        </el-form-item>

        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" placeholder="联系电话" />
        </el-form-item>

        <el-form-item label="地图位置" prop="longitude">
          <el-button type="primary" @click="handlerMapLocation()">选择位置</el-button>
        </el-form-item>

        <el-form-item label="商家地址" prop="address">
          <el-input v-model="form.address" placeholder="商家地址" />
        </el-form-item>

        <el-form-item label="商家图像" prop="picture">
          <el-upload
            class="avatar-uploader"
            :action="imageUploadUrl"
            :show-file-list="false"
            :headers="headers"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="form.picture" :src="form.picture" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancelForm">取 消</el-button>
      </div>

    </el-dialog>

    <!-- 修改密码-->
    <el-dialog title="更改密码" :visible.sync="pwdopen" width="500px" append-to-body :close-on-click-modal="false" :before-close="cancelForm">
      <el-form ref="formPwd" :model="formPwd" :rules="formpwdRules" label-width="100px">
        <el-form-item label="密码" prop="loginPwd">
          <el-input v-model="formPwd.loginPwd" placeholder="密码" />
        </el-form-item>

        <el-form-item label="确认密码" prop="reLoginPwd">
          <el-input v-model="formPwd.reLoginPwd" placeholder="确认密码" />
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input v-model="formPwd.phone" placeholder="手机号" />
          <div class="mix-input-btn">
            <el-link :disabled="btnSendVisable" @click="sendSms">{{ smsinfo }}</el-link>
          </div>
        </el-form-item>

        <el-form-item label="验证码" prop="code">
          <el-input v-model="formPwd.code" placeholder="请输入验证码" />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitPwdForm">确 定</el-button>
        <el-button @click="cancelpwdForm">取 消</el-button>
      </div>

    </el-dialog>

  </div>
</template>

<script>
import { commonDataApi } from '@/api/commonData.js'
import PageMinix from '@/mixin/PageMixin.js'
import AddOrEditMixin from '@/mixin/AddOrEditMixin.js'
import { dataListApi, findByIdApi, accountExists, editApi, changepwd } from '@/api/enterprise.js'
import { forgetpwd } from '@/api/sms.js'
import BaiduDisplay from '@/components/BaiduMap/display.vue'
import BaiduAddress from '@/components/BaiduMap/index.vue'
export default {
  components: {
    BaiduDisplay,
    BaiduAddress
  },
  mixins: [PageMinix, AddOrEditMixin],
  data() {
    // 验证用户名是否存在
    var accountFunction = (rule, value, callback) => {
      const params = { 'loginName': value, 'id': this.form.id }
      accountExists(params).then(resp => {
        if (resp.data) {
          callback(new Error(resp.data))
        } else {
          callback()
        }
      })
    }

    const phoneValidator = (rule, value, callback) => {
      const exp = /^0?(13|15|17|18|14|19)[0-9]{9}$/
      if (exp.test(value)) {
        this.btnSendVisable = false
        callback()
      } else {
        this.btnSendVisable = true
        callback(new Error('手机号格式不正确'))
      }
    }

    return {
      fetchDataApi: dataListApi,
      findByIdApi: findByIdApi,
      editApi: editApi,
      primaryKey: 'id',
      auditList: [],
      mapShow: false,
      // 更改密码
      pwdopen: false,
      formPwd: {},
      smsinfo: '发送验证码',
      // 短信倒计时动画时间，300秒
      countDownNum: 300,
      // 发送短信按钮是否禁用(true禁用，false启用 )
      btnSendVisable: true,
      rules: {
        loginName: [
          { required: true, message: '该值不能为空', trigger: 'blur' },
          { validator: accountFunction, trigger: 'blur' }
        ],
        name: [
          { required: true, message: '该值不能为空', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '该值不能为空', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '该值不能为空', trigger: 'blur' }
        ],
        longitude: [
          { required: true, message: '该值不能为空', trigger: 'blur' }
        ],
        latitude: [
          { required: true, message: '该值不能为空', trigger: 'blur' }
        ]
      },
      formpwdRules: {
        loginPwd: [
          { required: true, message: '该值不能为空', trigger: 'blur' }
        ],
        reLoginPwd: [
          { required: true, message: '该值不能为空', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '该值不能为空', trigger: 'blur' },
          { validator: phoneValidator, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '该值不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.initFormValue()
    this.fetchCommonData()
  },
  methods: {
    fetchCommonData() {
      commonDataApi().then(resp => {
        this.auditList = resp.data.auditData
      })
    },
    // 表单初始化值
    initFormValue() {
      this.form = {
        picture: undefined
      }
      this.formPwd = {
        uuid: undefined
      }
    },
    handleAduit(row) {
      console.log(row)
    },
    // 图片上传返回解析
    handleAvatarSuccess(res, file) {
      console.log(res)
      if (res.code !== 200) {
        this.$message.error(res.msg)
      } else {
        this.form.picture = 'http://localhost:8080' + res.data.image
      }
    },
    // 地图位置注册事件
    handlerLocation(resp) {
      console.log(resp)
      this.form.address = resp.address
      this.form.longitude = resp.longitude
      this.form.latitude = resp.latitude
      this.mapShow = false
    },
    // 加载地图定位模块
    handlerMapLocation() {
      this.mapShow = true
    },
    // 更改密码
    handleChangePwd(row) {
      this.pwdopen = true
      this.formPwd.id = row[this.primaryKey]
    },
    cancelpwdForm() {
      // element-ui内置方法
      if (this.$refs['formPwd']) {
        this.$refs['formPwd'].resetFields()
      }
      this.pwdopen = false
      // 自定义初始化值
      this.initFormValue()
    },
    // 修改密码保存
    submitPwdForm() {
      this.$refs['formPwd'].validate((valid) => {
        if (valid) {
          this.changePwdHandler()
        }
      })
    },
    // 更新密码操作
    changePwdHandler() {
      changepwd(this.formPwd).then(resp => {
        this.$message('更新密码成功')
        this.cancelpwdForm()
      })
    },
    // 发送验证码
    sendSms() {
      forgetpwd(this.formPwd.phone).then(resp => {
        this.formPwd.uuid = resp.data

        // 发送短信禁用，导计时
        this.btnSendVisable = true
        // 5分钟
        this.countDownNum = 300
        this.smsinfo = '(' + this.countDownNum + ')秒后重新发送'
        // 倒计时
        var tId = setInterval(() => {
          this.countDownNum--
          if (this.countDownNum === 0) {
            // 重新发送按钮启用
            this.btnSendVisable = false
            this.smsinfo = '发送验证码'
            clearInterval(tId)
          } else {
            this.smsinfo = '(' + this.countDownNum + ')秒后重新发送'
          }
        }, 1000)
      })
    }
  }
}
</script>

<style scoped>
  .avatar-uploader{
     width: 178px;
     overflow: hidden;
  }

  .avatar-uploader .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
      border-color: #409EFF;
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }
    .avatar {
      width: 178px;
      height: 178px;
      display: block;

    }

    .mix-input-btn {
        background: #fff;
        font-size: 12px;
        position: absolute;
        right: 2px;
        top: 10px;
        color: #303133;
        font-weight: 500;
        height: 20px;
        line-height: 20px;
        padding: 0 15px;
        border-left: 1px solid #dcdfe6;
        cursor: pointer;
    }
</style>

<style>

  .BMap_cpyCtrl {
    display: none;
  }

  .anchorBL {
    display: none;
  }
</style>
